package com.yequan.leetcode.tree.numIslands_200;

/**
 * @author : Administrator
 * @date : 2020/4/20
 */
public class RecodeNumIslands {

    private int row = 0;
    private int column = 0;

    /**
     * DFS
     * <p>
     * 1.遍历数组
     * 2.找出为 '1' 的位置,将其周围所有的 '1' 变为 '0', 并且计数
     *
     * @param grid
     * @return
     */
    public int numIslands(char[][] grid) {
        if (null == grid || grid.length == 0) {
            return 0;
        }
        row = grid.length;
        column = grid[0].length;
        int count = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (grid[i][j] == '1') {
                    markZero(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }

    private void markZero(char[][] grid, int i, int j) {
        if (i < 0 || i >= row || j < 0 || j >= column || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '0';
        //向右一步
        markZero(grid, i + 1, j);
        //向左一步
        markZero(grid, i - 1, j);
        //向上一步
        markZero(grid, i, j - 1);
        //向下一步
        markZero(grid, i, j + 1);
    }

}
